package no.ntnu.tdt4237;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.*;
import javax.mail.internet.*;

public class MailSender {

    private static void sendMail(String fromMail, String toMail, String subject, String text) {

        Properties props = new Properties();
        props.put("mail.smtp.host", Config.EMAIL_SMTP);
        props.put("mail.from", fromMail);
        Session session = Session.getInstance(props, null);

        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom();
            msg.setRecipients(Message.RecipientType.TO,
                    toMail);
            msg.setSubject(subject);
            msg.setSentDate(new Date());
            msg.setText(text);
            Transport.send(msg);
        } catch (MessagingException mex) {
            System.out.println("send failed, exception: " + mex);
        }
    }

    private static void sendMail(String fromMail, String toMail, String subject, URL link) {
        if (isValidEmail(toMail)) {
            Properties props = new Properties();
            props.put("mail.smtp.host", Config.EMAIL_SMTP);
            props.put("mail.from", fromMail);
            Session session = Session.getInstance(props, null);

            try {
                MimeMessage msg = new MimeMessage(session);
                msg.setFrom();
                msg.setRecipients(Message.RecipientType.TO,
                        toMail);
                msg.setSubject(subject);
                msg.setSentDate(new Date());

                msg.setText(String.valueOf(link));
                Transport.send(msg);
            } catch (MessagingException mex) {
                System.out.println("send failed, exception: " + mex);
            }
        }
    }

    public static void sendAvtivationCode(String toMail, String code) throws MalformedURLException {
        //URL link = new URL("http://localhost:8080/activate.jsp?ac=" + code);
        URL link = new URL("https://tdt4237m11.idi.ntnu.no:8457/activate.jsp?ac=" + code);
        //sendMail(Config.EMAIL_SENDER_ADR, toMail, "Activation code for UnSecureBlog", "This is your activation code: " + code);
        sendMail(Config.EMAIL_SENDER_ADR, toMail, "Activation code for UnSecureBlog", "Click this link to activate your user: " + link);
    }

    public static boolean isValidEmail(String email) {
        boolean isValid = false;
        //Initialize reg ex for email.  
        String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = email;
        //Make the comparison case-insensitive.  
        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }
    
    public static boolean sendNewPassword(String toMail){
        boolean success = false;
        String accepted = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String pwd = generatePassword(new Random(), accepted, 8);
        User u = Database.getUserByEmail(toMail);
        if(u != null && isValidEmail(toMail)){
            if(Database.changeUserPassword(u, pwd)){
                sendMail(Config.EMAIL_SENDER_ADR, toMail, "UnSecureBlog: Password reset", "Your new password is: " + pwd);
                success = true;
            }
        }
        return success;
    }
    
    public static String generatePassword(Random rng, String characters, int length){
        char[] text = new char[length];
        for (int i = 0; i < length; i++){
            text[i] = characters.charAt(rng.nextInt(characters.length()));
        }
        return new String(text);
    }
}